<script setup lang="ts">
import { ContentWrap } from '@/components/ContentWrap'
import { Search } from '@/components/Search'
import { useI18n } from '@/hooks/web/useI18n'
import { ElButton, ElMessageBox } from 'element-plus'
import { Dialog } from '@/components/Dialog'
import Edit from './components/Edit.vue'
import See from './components/See.vue'
import { unref } from 'vue'
// import { Table } from '@/components/Table'
import {
  spEnclosureLogOrderListApi,
  spEnclosureLogOrderAddAdminApi,
  spEnclosureLogOrderDelApi,
  spEnclosureLogOrderEndApi,
  spEnclosureLogOrderEditApi
} from '@/api/fa/enclosure'
import { useTable } from '@/hooks/web/useTableTest'
import { ref, reactive } from 'vue'
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
import { useIcon } from '@/hooks/web/useIcon'
import { useCache } from '@/hooks/web/useCache'
const { wsCache } = useCache()
const dict: any = wsCache.get('dict')
// const userInfo: any = wsCache.get('userInfo')
const getDictLabel = (type, value) => {
  let data = dict[type].find((item) => {
    return item.value == value
  })
  return data ? data.label : ''
}

const saveLoading = ref(false) //保存中的状态
const iconEdit = useIcon({ icon: 'ep:edit' })
const iconSee = useIcon({ icon: 'ep:view' })
const iconDel = useIcon({ icon: 'ep:delete' })
const iconEnd = useIcon({ icon: 'icon-park-outline:audit' })

const { register, tableObject, methods } = useTable<
  {
    total: number
    list: any[]
  },
  any
>({
  getListApi: spEnclosureLogOrderListApi,
  response: {
    data: 'data',
    count: 'count'
  }
})

const { getList, setSearchParams } = methods

getList()

const { t } = useI18n()
const crudSchemas = reactive<CrudSchema[]>([
  {
    field: 'id',
    label: '主键',
    fixed: 'left',
    width: 60,
    table: {
      show: true
    },
    form: {
      show: false
    },
    detail: {
      show: false
    }
  },
  {
    field: 'pasture_org_name',
    label: '牧场名称',
    fixed: 'left',
    search: {
      show: true
    },
    form: {
      show: false
    }
  },
  {
    field: 'number',
    label: '数量',
    width: 80,
    search: {
      show: false
    }
  },
  {
    field: 'type',
    label: '类型',
    width: 60,
    formatter: (_: Recordable, __: TableColumn, cellValue: number | string) => {
      return getDictLabel('enclosure_type', cellValue)
    },
    search: {
      component: 'Select',
      componentProps: {
        options: dict.enclosure_type
      },
      show: true
    }
  },
  {
    field: 'out_enclosure_name',
    label: '栏位（出）',
    search: {
      show: false
    }
  },
  {
    field: 'in_enclosure_name',
    label: '栏位（入）',
    search: {
      show: false
    }
  },
  {
    field: 'state',
    label: '状态',
    formatter: (_: Recordable, __: TableColumn, cellValue: number | string) => {
      return getDictLabel('out_in_state', cellValue)
    },
    width: 60,
    search: {
      component: 'Select',
      componentProps: {
        options: dict.out_in_state
      },
      show: true
    }
  },
  {
    field: 'note',
    label: '备注',
    search: {
      show: false
    }
  },
  {
    field: 'create_user_name',
    label: '创建人',
    search: {
      show: false
    }
  },
  {
    field: 'create_time',
    label: '创建时间',
    width: 170,
    form: {
      show: true,
      component: 'DatePicker',
      componentProps: {
        disabled: true,
        type: 'datetime',
        valueFormat: 'YYYY-MM-DD HH:mm:ss'
      }
    },
    search: {
      show: true,
      component: 'DatePicker',
      componentProps: {
        'is-range': true,
        'unlink-panels': true,
        rangeSeparator: 'To',
        type: 'daterange',
        valueFormat: 'YYYY-MM-DD HH:mm:ss'
      }
    }
  },
  {
    field: 'action',
    width: 200,
    fixed: 'right',
    label: t('tableDemo.action'),
    form: {
      show: false
    },
    detail: {
      show: false
    }
  }
])
const { allSchemas } = useCrudSchemas(crudSchemas)

const dialogVisible = ref(false)

const dialogTitle = ref('')

const actionType = ref('')

const action = async (type: string, row: any = {}) => {
  actionType.value = type
  switch (type) {
    case 'edit':
      dialogTitle.value = '编辑'
      tableObject.currentRow = row
      dialogVisible.value = true
      break
    case 'add':
      dialogTitle.value = '新增'
      tableObject.currentRow = {
        is_stop: '0'
      }
      dialogVisible.value = true
      break
    case 'see':
      dialogTitle.value = '查看'
      tableObject.currentRow = row
      dialogVisible.value = true
      break
    case 'del':
      ElMessageBox.confirm(`删除该出入栏记录？`, '删除', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          apiDel(row.id)
        })
        .catch(() => {})
      break
    case 'end':
      ElMessageBox.confirm(`归档后不能修改？`, '归档', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          apiEnd(row.id)
        })
        .catch(() => {})
      break
    default:
      console.log('未知类型')
  }
}
const apiDel = async (id) => {
  let delRes = await spEnclosureLogOrderDelApi({ id })
    .catch(() => {})
    .finally(() => {})
  if (delRes) {
    getList()
  }
}
const apiEnd = async (id) => {
  let delRes = await spEnclosureLogOrderEndApi({ id })
    .catch(() => {})
    .finally(() => {})
  if (delRes) {
    getList()
  }
}
const ids = ref([])
const checkedAll = ref(false)
const editRef = ref<ComponentRef<typeof Edit>>()
const save = async () => {
  const edit = unref(editRef)
  const dataInfo = await edit?.data
  const methods: any = await edit?.methods
  const { getSelections } = methods
  switch (actionType.value) {
    case 'add':
      await edit?.elFormRef?.validate(async (isValid) => {
        if (isValid) {
          saveLoading.value = true
          let selectDataInfo = ref({})
          await getSelections().then((res) => {
            selectDataInfo.value = res
            checkedAll.value = res.allCheck.value
            if (res.allCheck.value) {
              if (res.noSelectData.value.length > 0) {
                ids.value = res.noSelectData.value.map((element) => element.id)
              }
            } else {
              if (res.selectData.value.length > 0) {
                ids.value = res.selectData.value.map((element) => element.id)
              }
            }
          })
          const resIn = await spEnclosureLogOrderAddAdminApi({
            my_dept_id: dataInfo.admin_dept_id,
            pasture_org_id: dataInfo.pasture_org_id,
            pasture_dept_id: dataInfo.pasture_dept_id,
            pasture_user_id: dataInfo.pasture_user_id,
            type: dataInfo.type,
            date: dataInfo.date,
            out_enclosure_id: dataInfo.out_enclosure_id,
            in_enclosure_id: dataInfo.in_enclosure_id,
            checkedAll: checkedAll.value,
            selected: ids.value,
            note: dataInfo.note
          })
            .catch(() => {})
            .finally(() => {
              saveLoading.value = true
            })
          if (resIn) {
            dialogVisible.value = false
            getList()
          }
          dialogVisible.value = false
        }
      })
      break
    case 'edit':
      await edit?.elFormRef?.validate(async (isValid) => {
        if (isValid) {
          saveLoading.value = false
          let selectDataInfo = ref({})
          await getSelections().then((res) => {
            selectDataInfo.value = res
            checkedAll.value = res.allCheck.value
            if (res.allCheck.value) {
              if (res.noSelectData.value.length > 0) {
                ids.value = res.noSelectData.value.map((element) => element.id)
              }
            } else {
              if (res.selectData.value.length > 0) {
                ids.value = res.selectData.value.map((element) => element.id)
              }
            }
          })
          console.log(dataInfo, 'dataInfo')

          const resIn = await spEnclosureLogOrderEditApi({
            id: dataInfo.id,
            my_dept_id: dataInfo.admin_dept_id,
            pasture_org_id: dataInfo.pasture_org_id,
            pasture_dept_id: dataInfo.pasture_dept_id,
            pasture_user_id: dataInfo.pasture_user_id,
            type: dataInfo.type,
            date: dataInfo.date,
            out_enclosure_id: dataInfo.out_enclosure_id,
            in_enclosure_id: dataInfo.in_enclosure_id,
            checkedAll: checkedAll.value,
            selected: ids.value,
            note: dataInfo.note
          })
            .catch(() => {})
            .finally(() => {
              saveLoading.value = true
            })
          if (resIn) {
            dialogVisible.value = false
            getList()
          }
          dialogVisible.value = false
        }
      })
      break
    default:
      console.log('未知类型')
  }
}

const getRowKeys = (row) => {
  return row
}
</script>

<template>
  <ContentWrap>
    <Search :schema="allSchemas.searchSchema" @search="setSearchParams" @reset="setSearchParams" />
    <div class="mb-10px">
      <ElButton type="primary" @click="action('add')">新增</ElButton>
    </div>
    <Table
      v-model:pageSize="tableObject.pageSize"
      v-model:currentPage="tableObject.currentPage"
      :columns="allSchemas.tableColumns"
      :data="tableObject.tableList"
      :loading="tableObject.loading"
      :border="true"
      :pagination="{
        total: tableObject.count
      }"
      :row-key="getRowKeys"
      @register="register"
      :selection="false"
    >
      <template #action="{ row }">
        <ElButton circle :icon="iconSee" @click="action('see', row)" title="查看" />
        <ElButton
          v-if="row.state == 1"
          circle
          :icon="iconEdit"
          @click="action('edit', row)"
          title="编辑"
        />
        <ElButton
          v-if="row.state == 1"
          circle
          :icon="iconEnd"
          @click="action('end', row)"
          title="归档"
        />
        <ElButton
          v-if="row.state == 1"
          circle
          :icon="iconDel"
          @click="action('del', row)"
          title="删除"
        />
      </template>
    </Table>
  </ContentWrap>
  <Dialog v-model="dialogVisible" :title="dialogTitle">
    <Edit v-if="actionType == 'add'" ref="editRef" />
    <Edit
      v-if="actionType == 'edit'"
      ref="editRef"
      :current-row="tableObject.currentRow"
      :id="Number(tableObject.currentRow.id)"
    />
    <See
      v-if="actionType == 'see'"
      :current-row="tableObject.currentRow"
      :detail-schema="allSchemas.detailSchema"
    />
    <template #footer>
      <ElButton
        v-if="actionType == 'add' || actionType == 'edit'"
        type="primary"
        :loading="saveLoading"
        @click="save()"
      >
        保存
      </ElButton>
      <ElButton @click="dialogVisible = false">关闭</ElButton>
    </template>
  </Dialog>
</template>
